package net.sansi.v3correctserver.service.photorec.impl;

import net.sansi.v3correctserver.entity.IntPoint;
import net.sansi.v3correctserver.entity.analyse.PhotoAnalyseResult;
import net.sansi.v3correctserver.entity.image.RecImage;
import net.sansi.v3correctserver.entity.photorec.LedNode;
import net.sansi.v3correctserver.service.photorec.RecService;
import net.sansi.v3correctserver.service.photorec.rec.RecRectScreen;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Fang
 * create time : 2024/11/4
 * IDE : IntelliJ IDEA
 * <p>
 * 图像识别服务
 */
@Service
public class RecServiceImpl implements RecService {

    /**
     * 矩形屏相片分析
     *
     * @param ledPhoto   灯点相片
     * @param blackPhoto 黑色相片
     * @param fence      围栏
     * @return 矩形屏相片分析结果
     */
    public PhotoAnalyseResult.Rect rectPhoto(RecImage ledPhoto, RecImage blackPhoto, List<IntPoint> fence) {
        RecRectScreen rec = new RecRectScreen(ledPhoto, blackPhoto, fence).toRec();

        PhotoAnalyseResult.Rect res = new PhotoAnalyseResult.Rect();
        res.setXDistance(rec.getLedDistanceX());
        res.setYDistance(rec.getLedDistanceY());
        res.setRecWidth(rec.getMatrix().getWidth());
        res.setRecHeight(rec.getMatrix().getHeight());
        res.setEmpties(rec.getEmpties().size());
        res.setConflicts(rec.getConflictNodes().size());

        double pixelRatio = 0;
        double saturation = 0;
        long pixelArea = 0;
        if (rec.getMatrix().getItemSize() == 0) return res;
        int w = rec.getMatrix().getWidth(), h = rec.getMatrix().getHeight();
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                LedNode led = rec.getMatrix().get(x, y);
                if (led == null) continue;
                pixelRatio += led.getArea() * 1.0 / led.getBrightFenceArea();
                saturation += led.ledColor.getSaturation();
                pixelArea += led.getArea();
            }
        }
        int count = rec.getMatrix().getItemSize();
        res.setPixelRatio(pixelRatio / count);
        res.setSaturation(saturation / count);
        res.setPixelArea((int) (pixelArea / count));
        LedNode led = rec.getLedByBrightSort(0.5);
        res.setLedBrightness(led.getBrightness());
        res.setLedPixelAvgBrightness(led.getBrightness() / led.getArea());
        return res;
    }

}
